<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/9/19
 * Time: 10:25
 */
namespace App\MultiTrait;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Config;

trait PassportTrait
{
    /**
     * 登录
     * @param string $guard
     * @param array $config
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function authenticate($guard = '', $config = [])
    {
        $client = new Client();

        try {
            $url = request()->root() . '/' . $guard . '/oauth/token';

            $params = array_merge($config, [
                'provider' => $guard
            ]);

            $response = $client->post($url, ['form_params' => $params]);
        } catch (RequestException $exception) {
            abort(401, $exception->getMessage());
        }

        if ($response->getStatusCode() !== 401) {
            return json_decode($response->getBody()->getContents(), true);
        }

        abort(401, '账号或密码错误');
    }

    /**
     * 刷新token
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getRefreshToken()
    {
        $client = new Client();

        try {
            $url = request()->root() . '/oauth/token';

            $params = array_merge(config('passport.proxy'), [
                'refresh_token' => request('refresh_token'),
            ]);

            $response = $client->post($url, ['form_params' => $params]);
        } catch (RequestException $exception) {
            abort(401, '请求失败，服务器错误');
        }

        if ($response->getStatusCode() !== 401) {
            return json_decode($response->getBody()->getContents(), true);
        }

        abort(401, 'refresh_token 错误');
    }
}
